package org.telegram.bot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BooleanEnum;
import com.ruoyi.system.service.ISysUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.telegram.bot.domain.*;
import org.telegram.bot.emums.BotCommonEnums;
import org.telegram.bot.handle.IBotSendMessage;
import org.telegram.bot.mapper.*;
import org.telegram.bot.mq.producer.GroupCacheRefreshProducer;
import org.telegram.bot.service.*;
import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatAdministrators;
import org.telegram.telegrambots.meta.api.objects.chat.Chat;
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMember;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 群组Service业务层处理
 *
 * @author wyx
 * @date 2023-08-17
 */
@Slf4j
@Service
public class BotGroupServiceImpl implements IBotGroupService, IBotSendMessage
{
    @Resource
    private BotGroupMapper botGroupMapper;
    
    @Resource
    private BotChatMemberMapper botChatMemberMapper;
    
    @Resource
    private BotChatWelcomeMapper botChatWelcomeMapper;
    @Resource
    private BotConfigWordMapper botConfigWordMapper;
    
    @Resource
    private BotJobMapper botJobMapper;
    
    @Resource
    private BotKeyWordReplyMapper botKeyWordReplyMapper;
    
    @Resource
    private BotProhibitedWordsMapper botProhibitedWordsMapper;

    @Resource
    private ISysUserService sysUserService;
    
    @Resource
    private IBotChatMemberService chatMemberService;
    
    @Resource
    private IBotChatVerifyService chatVerifyService;
    
    @Resource
    private IBotConfigWordService configWordService;
    
    @Resource
    private IBotKeyWordReplyService keyWordReplyService;
    
    @Resource
    private IBotProhibitedWordsService prohibitedWordsService;
    
    @Resource
    private IBotGroupJoinService botGroupJoinService;
    
    @Resource
    private IBotBanEmojiService botBanEmojiService;
    
    @Resource
    private GroupCacheRefreshProducer groupCacheRefreshProducer;
    
    //缓存
    private static final Map<Long, BotGroup> botGroupCache = new ConcurrentHashMap<>();
    
    
    /**
     * 查询群组
     *
     * @param id 群组主键
     * @return 群组
     */
    @Override
    public BotGroup selectBotGroupById(Long id)
    {
        return botGroupMapper.selectById(id);
    }

    /**
     * 查询群组列表
     *
     * @param botGroup 群组
     * @return 群组
     */
    @Override
    public List<BotGroup> selectBotGroupList(BotGroup botGroup)
    {
        List<Long> joinChatList = chatMemberService.getJoinChatList();
        if(!CollectionUtils.isEmpty(joinChatList)){
            botGroup.setChatIds(joinChatList);
        }
        else{
         return new ArrayList<>();
        }
        return botGroupMapper.selectBotGroupList(botGroup);
    }

    /**
     * 新增群组
     *
     * @param botGroup 群组
     * @return 结果
     */
    @Override
    public int insertBotGroup(BotGroup botGroup)
    {
        return botGroupMapper.insert(botGroup);
    }

    /**
     * 修改群组
     *
     * @param botGroup 群组
     * @return 结果
     */
    @Override
    public int updateBotGroup(BotGroup botGroup)
    {
        return botGroupMapper.updateById(botGroup);
    }

    /**
     * 批量删除群组
     *
     * @param ids 需要删除的群组主键
     * @return 结果
     */
    @Override
    public int deleteBotGroupByIds(Long[] ids)
    {
        return botGroupMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除群组信息
     *
     * @param id 群组主键
     * @return 结果
     */
    @Override
    public int deleteBotGroupById(Long id)
    {
        return botGroupMapper.deleteById(id);
    }
    
    /**
     * 统一更新聊天组ID
     * @param newChatId
     * @param oldChatId
     * @return
     */
    @Override
    public int updateChatId(Long newChatId, Long oldChatId){
        int rows = 0;
        List<String> tableNameList = new ArrayList<>();
        tableNameList.add("bot_group");
        tableNameList.add("bot_chat_member");
        tableNameList.add("bot_chat_verify");
        tableNameList.add("bot_chat_welcome");
        tableNameList.add("bot_config_word");
        tableNameList.add("bot_key_word_reply");
        tableNameList.add("bot_prohibited_words");
        tableNameList.add("bot_group_join");
        for (String tableName : tableNameList) {
            rows += botGroupMapper.deleteChatId(newChatId,tableName);
        }
        //判断自动创建的新群是否还存在，如果群组就不执行变更记录，否则会导致出现两条数据
        Long l = botGroupMapper.selectCount(new LambdaQueryWrapper<>(BotGroup.class).eq(BotGroup::getChatId, newChatId));
        //确保删除完整后在变更
        if(l==0){
            for (String tableName : tableNameList) {
                rows += botGroupMapper.updateChatId(newChatId,oldChatId,tableName);
            }
        }
        return rows;
    }
    /**
     * 初始化群管理
     * @param botId
     * @param chat
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTelegramGroup(String botId,Chat chat){
        if(!BotCommonEnums.CHAT_TYPE_SUPERGROUP.equals(chat.getType()) && !BotCommonEnums.CHAT_TYPE_GROUP.equals(chat.getType()) && !BotCommonEnums.CHAT_TYPE_CHANNEL.equals(chat.getType())){
            return false;
        }
        BotGroup group = botGroupMapper.selectOne(new LambdaQueryWrapper<BotGroup>().eq(BotGroup::getChatId, chat.getId()));
            if(group == null){
                group = new BotGroup();
                //初始化数据
                botGroupMapper.insert(group.setChatId(chat.getId()).setType(chat.getType()).setTitle(chat.getTitle()).setUserName(chat.getUserName()));
            }
            else {
                group.setTitle(chat.getTitle());
                group.setUserName(chat.getUserName());
                group.setType(chat.getType());
                botGroupMapper.updateById(group);
            }
            //获取当前群的管理员
            List<ChatMember> administrators = send(botId, GetChatAdministrators.builder().chatId(chat.getId()).build());
            if(!CollectionUtils.isEmpty(administrators)){
                List<SysUser> sysUsers = new ArrayList<>();
                List<BotChatMember> botChatMembers = new ArrayList<>();
                for (ChatMember administrator : administrators) {
                    SysUser sysUser = new SysUser();
                    sysUser.setUserId(administrator.getUser().getId());
                    sysUser.setUserName(administrator.getUser().getId().toString());
                    String nickName = administrator.getUser().getId().toString();
                    if(StringUtils.hasText(administrator.getUser().getFirstName())){
                        nickName = administrator.getUser().getFirstName();
                    }
                    if(StringUtils.hasText(administrator.getUser().getLastName())){
                        nickName += administrator.getUser().getLastName();
                    }
                    sysUser.setNickName(nickName);
                    sysUser.setDeptId(BotCommonEnums.DEFAULT_DEPT_ID);
                    sysUser.setRoleIds(new Long[]{BotCommonEnums.DEFAULT_ROLE_ID});
                    sysUser.setPassword(administrator.getUser().getId().toString() + administrator.getUser().getId());
                    sysUsers.add(sysUser);
                    //群成员关联
                    BotChatMember botChatMember = new BotChatMember();
                    botChatMember.setUserId(administrator.getUser().getId());
                    botChatMember.setUserName(administrator.getUser().getUserName());
                    botChatMember.setFirstName(administrator.getUser().getFirstName());
                    botChatMember.setLastName(administrator.getUser().getLastName());
                    botChatMember.setRole(administrator.getStatus());
                    botChatMember.setBot(administrator.getUser().getIsBot()?BooleanEnum.TRUE.getStr():BooleanEnum.FALSE.getStr());
                    //premium
                    botChatMember.setPremium(administrator.getUser().getIsPremium()!=null && administrator.getUser().getIsPremium()?BooleanEnum.TRUE.getStr():BooleanEnum.FALSE.getStr());
                    botChatMembers.add(botChatMember);
                }
                sysUserService.importUser(sysUsers,true,chat.getId().toString());
                chatMemberService.chatSaveAndUpdate(botChatMembers,chat.getId());
            }
            //初始化校验
            chatVerifyService.init(chat.getId());
            //违禁词配置初始化
            configWordService.init(chat.getId());
            //初始机器人加入的群
            botGroupJoinService.updateBotGroupJoinChat(chat.getId(),botId);
            //更新缓存信息
        groupCacheRefreshProducer.sendMessage(chat.getId());
        return true;
    }
    
    @Override
    public void clearGroup(String botId, Long chatId) {
        botGroupMapper.delete(new LambdaUpdateWrapper<BotGroup>().eq(BotGroup::getChatId,chatId));
        chatMemberService.deleteBotChatMemberByChatId(chatId);
        botChatMemberMapper.delete(new LambdaUpdateWrapper<BotChatMember>().eq(BotChatMember::getChatId,chatId));
        botChatWelcomeMapper.delete(new LambdaUpdateWrapper<BotChatWelcome>().eq(BotChatWelcome::getChatId,chatId));
        botConfigWordMapper.delete(new LambdaUpdateWrapper<BotConfigWord>().eq(BotConfigWord::getChatId,chatId));
        botJobMapper.delete(new LambdaUpdateWrapper<BotJob>().eq(BotJob::getChatId,chatId));
        botKeyWordReplyMapper.delete(new LambdaUpdateWrapper<BotKeyWordReply>().eq(BotKeyWordReply::getChatId,chatId));
        botProhibitedWordsMapper.delete(new LambdaUpdateWrapper<BotProhibitedWords>().eq(BotProhibitedWords::getChatId,chatId));
        botGroupJoinService.deleteBotGroupJoinChat(chatId,botId);
        botBanEmojiService.deleteBotBanEmojiByChatId(chatId);
        groupCacheRefreshProducer.sendMessage(chatId);
    }
    
    /**
     * 简单的群组下拉 默认过滤频道
     * @return
     */
    @Override
    public List<BotGroup> selectSimpleList(){
       return selectSimpleList(true);
    }
    /**
     * 简单的群组下拉过滤频道
     * @param filterChannel true
     * @return
     */
    @Override
    public List<BotGroup> selectSimpleList(Boolean filterChannel){
        List<BotGroup> list = new ArrayList<>();
        List<Long> chats = chatMemberService.getJoinChatList();
        if(!CollectionUtils.isEmpty(chats)){
            LambdaQueryWrapper<BotGroup> query = new LambdaQueryWrapper<BotGroup>().select(BotGroup::getChatId, BotGroup::getTitle).in(BotGroup::getChatId, chats);
            if(filterChannel){
                //type不等于channel的群组
                query.ne(BotGroup::getType,BotCommonEnums.CHAT_TYPE_CHANNEL);
            }
            //查询群组
            list = botGroupMapper.selectList(query);
        }
        return list;
    }
    
    @Override
    public Map<Long,BotGroup> selectGroupToMap(List<Long> chatIds){
        List<BotGroup> botGroups = botGroupMapper.selectList(new LambdaQueryWrapper<BotGroup>().in(BotGroup::getChatId, chatIds));
        //botGroups根据chatId转成map
        return botGroups.stream().collect(Collectors.toMap(BotGroup::getChatId,item->item));
    }
    
    @Override
    public void messageTextCheck(BotMessageTextCheck messageTextCheck){
        //私聊、频道不处理
        if(BotCommonEnums.CHAT_TYPE_PRIVATE.equals(messageTextCheck.getChatType()) || BotCommonEnums.CHAT_TYPE_CHANNEL.equals(messageTextCheck.getChatType())){
            return;
        }
        //false 校验通过、没有违禁词
        boolean has = prohibitedWordsService.checkText(messageTextCheck);
       
        if(!has){
            //没有违禁词
            keyWordReplyService.checkMessageReply(messageTextCheck.getText(), messageTextCheck.getBotId(), messageTextCheck.getChatId(), messageTextCheck.getUserId(), messageTextCheck.getMessageId());
        }
    }
}
